const ONLINE = 0;
const OFFLINE = 1;
import {
  getOrderList, cancelOrder, buy, confirmDelivery,
  confirmReturn, payOrder, renewal, getSettle
} from '../../services/order';
const position = ['top', 'topRight', 'rightTop', 'right', 'rightBottom', 'bottomRight', 'bottom', 'bottomLeft', 'leftBottom', 'left', 'leftTop', 'topLeft'];

Page({
  data: {

    position: position[0],
    show: false,
    showMask: true,
    showIcon: true,

    modalOpened: false,
    defaultTitle: "下拉刷新",
    pullRefresh: true,
    tabIndex: 0,
    returnExpressNo: '',
    returnExpressName: '',
    lostMoney: '',
    damageMoney: '',
    violateMoney: '',
    totalMoney: '',
    settleRemark: '',

    orderId: 0,
    totalpage: 1,
    show: false, // 是否显示加载动画
    page: 1, // 当前页数
    list: [], // 页面List数据
    ONLINE,
    OFFLINE,
    tabs: [
      {
        id: 0,
        title: '全部',
        orderStatus: '',
        onClick: () => { },
      },
      {
        id: 1,
        title: '待付款',
        onClick: () => { },
      },
      {
        id: 2,
        title: '待发货',
        onClick: () => { },
      },
      {
        id: 3,
        title: '租用中',
        onClick: () => { },
      },
      {
        id: 4,
        title: '已完成',
        onClick: () => { },
      }
    ],
    tickets: [
      {
        id: 0,
        price: 30,
        baseline: 300,
        startAt: '2019.4.01',
        endAt: '2019.12.31',
        action: 0
      },
      {
        id: 0,
        price: 30,
        baseline: 300,
        startAt: '2019.4.01',
        endAt: '2019.12.31',
        action: 1
      },
      {
        id: 0,
        price: 30,
        baseline: 300,
        startAt: '2019.4.01',
        endAt: '2019.12.31',
        action: 2
      },
    ],
    activeId: 0,
  },

  onNextPositionTap() {

    let index = position.indexOf(this.data.position);

    index = index >= position.length - 1 ? 0 : index + 1;

    this.setData({

      show: true,

      position: position[index],

    });

  },

  onShow() {
    my.setNavigationBar({
      title: '我的订单',
      backgroundColor: '#4BA3F9'
    })
  },
  onLoad(event) {
    console.log(event)
    this.setData({ orderStatus: parseInt(event.orderStatus), activeId: parseInt(event.orderStatus) })
    // this.mySchedulde();
    this.getOrderList()
  },

  onTabItemTap(id) {
    console.log(id);
    this.setData({ activeId: id, orderStatus: id });
    my.startPullDownRefresh()
  }, onPullDownRefresh() {
    let that = this
    this.setData({
      list: [],
      page: 1,
      pages: 1
    });
    setTimeout(function () {
      that.getOrderList()
    }, 1000)
  },
  stopPullDownRefresh() {
    my.stopPullDownRefresh({
      complete(res) {
        console.log(res, new Date())
      }
    })
  },
  async getOrderList() {

    let param = {
      pageNum: this.data.page,
      pageSize: 20
    }
    if (this.data.orderStatus > 0) {
      switch (this.data.orderStatus) {
        case 1:
          param.orderStatus = 'WAITING_PAYMENT'
          break;
        case 2:
          param.orderStatus = 'WAITING_BUSINESS_DELIVERY'
          break;
        case 3:
          param.orderStatus = 'WAITING_GIVE_BACK'
          break;
        case 4:
          param.orderStatus = 'ORDER_FINISH'
          break;
        default:
          break;
      }
    }
    let that = this
    getOrderList(param).then((res) => {
      console.log(res)
      if (res.code == "000000") {
        this.setData({ totalpage: res.data.pages });
        res.data.list.forEach(element => {
          let orderStatusName = ''
          let isCanCancel = false//可取消
          let isCanPay = false//可支付
          let isCanLookDelivery = false//可查看物流
          let isCanBack = false //可以确认归还
          let isCanBackOrderStatus = false //可以确认归还主状态
          let isCanBackSubstatus = false //可以确认归还子状态
          let isCanconfirmDelivery = false //可以确认收货
          let isCanLookSettle = false //可以查看结算单
          let isCanBuyOut = false //可以买断
          let isCanRelet = false //可以续租
          let isCanLookStage = true//查看分期账单
          switch (element.orderStatus) {
            case 'USER_CANCELED_CLOSED':
              orderStatusName = '用户取消'
              break;
            case 'BUSINESS_CANCELED_CLOSED':
              orderStatusName = '商家取消'
              break;
            case 'ALREADY_FREEZE':
              orderStatusName = '金额已冻结'
              isCanCancel = true
              isCanPay = true
              isCanLookStage = false
              break;
            case 'WAITING_PAYMENT':
              orderStatusName = '待付款'
              isCanCancel = true
              isCanPay = true
              isCanLookStage = false
              break;
            case 'USER_OVERTIME_PAYMENT_CLOSED':
              orderStatusName = '超时支付关闭'
              break;
            case 'DELIVERY_OVERTIME_CLOSED':
              orderStatusName = '超时发货关闭'
              break;
            case 'WAITING_BUSINESS_DELIVERY':
              orderStatusName = '待发货'
              isCanCancel = true
              break;
            case 'WAITING_USER_RECEIVE_CONFIRM':
              orderStatusName = '待收货'
              isCanconfirmDelivery = true
              break;
            case 'WAITING_GIVE_BACK':
              orderStatusName = '租用中'
              isCanBack = true;
              isCanBuyOut = true;
              isCanRelet = true;
              break;
            case 'WAITING_SETTLEMENT':
              orderStatusName = '待结算'
              isCanBuyOut = true
              isCanBackOrderStatus = true;
              break;
            case 'WAITING_SETTLEMENT_PAYMENT':
              orderStatusName = '待结算付款'
              isCanLookSettle = true
              break;
            case 'ORDER_FINISH':
              orderStatusName = '已完成'
              break;
            case 'RENEWAL_SUCCESS':
              orderStatusName = '续租成功'
              isCanBack = true
              isCanBuyOut = true
              isCanRelet = true
              break;
          }
          if (element.subStatus == 'WAITING_UPLOAD_RETURNING_INFO') {
            isCanBackSubstatus = true;
          }
          if (isCanBackOrderStatus && isCanBackSubstatus) {
            isCanBack = true;
          }

          element.isCanCancel = isCanCancel
          element.isCanPay = isCanPay
          element.isCanLookDelivery = isCanLookDelivery
          element.isCanBack = isCanBack
          element.isCanconfirmDelivery = isCanconfirmDelivery
          element.isCanLookSettle = isCanLookSettle
          element.isCanBuyOut = isCanBuyOut
          element.isCanRelet = isCanRelet
          element.isCanLookStage = isCanLookStage
          element.orderStatusName = orderStatusName
        });
        this.setData({
          list: this.data.list.concat(res.data.list),
          show: false
        });

      }
      this.stopPullDownRefresh()
    })

  },
  /**
  * scroll-view滑到底部触发事件
  * @method scrollMytrip
  */
  async scrollMytrip() {
    try {
      // 判断是否还有数据需要加载
      if (this.data.page < this.data.pages) {
        this.setData({ show: true });
        this.setData({ page: this.data.page + 1 });
        this.getOrderList();
      }
    } catch (e) {
      this.setData({ show: false });
      console.log('scrollMytrip执行异常:', e);
    }
  },
  toKf() {
    my.switchTab({
      url: '/pages/customer/customer',
    })
  },
  todetail(event) {
    my.navigateTo({
      url: '/pages/orderDetail/orderDetail?orderId=' + event.target.dataset.id,
    })

  },
  lookstage(event) {
    my.navigateTo({
      url: '/pages/billStages/index?orderId=' + event.target.dataset.id,
    })
  },
  cancelOrder(event) {
    my.prompt({
      title: '取消订单',
      message: '请填写取消原因',
      okButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.ok) {
          if (result.inputValue.length <= 0) {
            my.showToast({
              type: 'fail',
              content: '请填写取消原因',
              duration: 2000,
            });
            return
          }
          cancelOrder({ orderId: event.target.dataset.id, cancelReason: result.inputValue }).then(res => {
            if (res.code == "000000") {
              my.startPullDownRefresh()
            }
          })
        }

      },
    });
  },

  confirmDelivery(event) {

    my.confirm({
      title: '温馨提示',
      content: '确定收货吗?',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          confirmDelivery({ orderId: event.target.dataset.id }).then(res => {
            if (res.code == "000000") {
              my.startPullDownRefresh()
            }
          })
        }
      },
    });

  },
  byuout(event) {
    my.confirm({
      title: '温馨提示',
      content: '确定买断吗?',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          buy({ orderId: event.target.dataset.id }).then(res => {
            if (res.code == "000000") {
              this.onpayOrder(event.target.dataset.id, res.data)
            }
          })
        }
      },
    });
  }
  ,
  relet(event) {
    my.confirm({
      title: '温馨提示',
      content: '确定续租吗?',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          renewal({ orderId: event.target.dataset.id }).then(res => {
            if (res.code == "000000") {
              my.startPullDownRefresh()
            }
          })
        }
      },
    });
  }
  ,

  onItemInput(e) {

    this.setData({

      [e.target.dataset.field]: e.detail.value,

    });

  },
  onClear(e) {

    this.setData({

      [e.target.dataset.field]: '',

    });

  },
  openModal(event) {
    let orderId = event.target.dataset.id
    this.setData({
      modalOpened: true,
      returnExpressName: '',
      returnExpressNo: '',
      orderId: orderId
    });

  },
  onModalClose2() {
    this.setData({
      modalOpened2: false,
    });
  },
  onModalClose() {
    this.setData({
      modalOpened: false,
    });
  },
  looksettle(event) {
    getSettle({ orderId: event.target.dataset.id }).then(res => {
      if (res.code == "000000") {
        this.setData({
          modalOpened2: true,
          lostMoney: res.data.lostMoney,
          violateMoney: res.data.violateMoney,
          totalMoney: res.data.totalMoney,
          damageMoney: res.data.damageMoney,
          settleRemark: res.data.settleRemark
          ,
          orderId: event.target.dataset.id
        });
      }
    })

  }
  ,

  backorder() {
    if (this.data.returnExpressNo.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请填写快递单号',
        duration: 2000,
      });
      return
    }
    if (this.data.returnExpressName.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请填写快递名称',
        duration: 2000,
      });
      return
    }

    confirmReturn({
      orderId: this.data.orderId,
      returnExpressName: this.data.returnExpressName,
      returnExpressNo: this.data.returnExpressNo
    }).then(res => {
      if (res.code == "000000") {
        this.onModalClose()
        my.startPullDownRefresh()
      }
    })

  },
  lookdelivery(event) {

  },
  onpayOrder(orderID, data) {
    if (data.payType == 0) {
      my.showToast({
        type: 'fail',
        content: data.payData,
        duration: 2000,
      });
      return
    } else if (data.payType == 1) {
      my.tradePay({
        tradeNO: data.payData,
        success: function (res3) {
          console.log(res3)
          // let resultAli = JSON.stringify(res3)
          let resultAli = res3
          if (resultAli.resultCode == "9000") {
            my.startPullDownRefresh()
          } else {
            my.showToast({
              type: 'fail',
              content: resultAli.memo,
              duration: 2000,
            });
          }

        },
        fail: function (res) {
          console.log(res)
          // my.alert({
          //   content: JSON.stringify(res),
          // });
        },
      });
    }
    else if (data.payType == 2) {
      my.tradePay({
        // 调用资金冻结接口（alipay.fund.auth.order.app.freeze），获取资金授权参数
        orderStr: data.payData,
        success: (res3) => {

          console.log(res3)
          // let resultAli = JSON.stringify(res3)
          let resultAli = res3
          if (resultAli.resultCode == "9000") {
            my.startPullDownRefresh()
          } else {
            my.showToast({
              type: 'fail',
              content: resultAli.memo,
              duration: 2000,
            });
          }
        },
        fail: (res) => {
          console.log(res)
          // my.alert({
          //   content: JSON.stringify(res),
          // });
        }
      });
    }
  },

  payOrder(event) {
    let orderID = event.target.dataset.id
    payOrder({
      orderId: orderID
    }).then(res2 => {
      if (res2.code == "000000") {
        this.onpayOrder(orderID, res2.data)
      }
    })
  },
  payorder2(event) {

    payOrder({
      orderId: this.data.orderId
    }).then(res2 => {
      if (res2.code == "000000") {
        this.onpayOrder(this.data.orderId, res2.data)
        this.onModalClose2()
      }
    })
  }
});
